package pox.channel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

public class SharedStringWrite implements Runnable {
	static String PATH = "E:/poiExcel/test/";

	static boolean end = false;

	@Override
	public void run() {
		end = false;
		try {
			long date = System.currentTimeMillis();
			FileOutputStream sheetFile = new FileOutputStream(PATH + "xl/sharedStrings.xml");
			// count=\"6\"
			String headstr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> <sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" count=\"countLen\"　　　　　　　　　　　　　　　　 >";
			String str = SharedStringChannel.getSharedString();
			sheetFile.write(headstr.getBytes());
			int index = 0;
			StringBuffer sb = new StringBuffer();
			while (str != null) {
				index++;
				// 每10个内容写一次文件
				sb.append(str);
				if (index % 10 == 0) {
					sheetFile.write(sb.toString().getBytes());
					sb = new StringBuffer();
				}
				str = SharedStringChannel.getSharedString();
			}
			if (sb.length() > 0) {
				sheetFile.write(sb.toString().getBytes());
			}
			sheetFile.write("</sst>".getBytes());
			sheetFile.close();
			// 替换文件中数量描述
			RandomAccessFile accessFile = new RandomAccessFile(new File(PATH + "xl/sharedStrings.xml"), "rwd");
			headstr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> <sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" count=\"countLen\"";
			headstr = headstr.replace("countLen", (SharedStringChannel.getIndex() + 1) + "");
			headstr += "          ";
			accessFile.seek(0);
			System.out.println(headstr);
			accessFile.writeBytes(headstr);
			accessFile.close();
			System.out.println("run" + (System.currentTimeMillis() - date));
			end = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static boolean isEnd() {
		return end;
	}

	public static void main(String[] args) {
		String headstr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> <sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"　count=\"countLen\"　　　　　> ";
		System.out.println(headstr.getBytes().length);
		headstr = headstr.replace("countLen", "5");
		System.out.println(headstr.getBytes().length);
		System.out.println(headstr);
	}
}